package com.xmg.nio.groupchart;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class GroupChatServer {
    //定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private final static int PORT = 6667;

    public GroupChatServer() {
        try {
            selector = Selector.open();
            listenChannel = ServerSocketChannel.open();
            listenChannel.bind(new InetSocketAddress(PORT));
            listenChannel.configureBlocking(false);
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public void  listen(){
        while (true){
            try{
                int count = selector.select(2000);
                if(count>0){
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        if(key.isAcceptable()){
                            SocketChannel channel = listenChannel.accept();
                            channel.configureBlocking(false);
                            channel.register(selector,SelectionKey.OP_READ);
                            System.out.println(channel.getRemoteAddress()+" 上线了 ");
                        }else if(key.isReadable()){
                            //编写专门的方法处理读操作
                            read(key);
                        }
                        //删除掉当前key，防止重复处理
                        iterator.remove();
                    }
                }
            }catch (IOException e){

            }finally {

            }
        }
    }

    private void read(SelectionKey key){
        SocketChannel channel = null;
        try {
            channel = (SocketChannel) key.channel();
            ByteBuffer allocate = ByteBuffer.allocate(1024);
            int count = channel.read(allocate);
            if (count>0){
                String msg = new String(allocate.array());
                System.out.println("from 客户端："+msg);
                //向其他用户转发消息，需要去除自己
                sendToOtherClient(msg,channel);
            }
        }catch (Exception e){
            try {
                System.out.println(channel.getRemoteAddress() + "  离线了 ");
                key.channel();
                channel.close();
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
    }

    private void sendToOtherClient(String msg,SocketChannel self) throws IOException {
        for (SelectionKey key : selector.keys()) {
            Channel channel = key.channel();
            if(channel instanceof SocketChannel && channel != self){
                ByteBuffer wrap = ByteBuffer.wrap(msg.getBytes());
                SocketChannel socketChannel = (SocketChannel) channel;
                socketChannel.write(wrap);
            }
        }
    }

    public static void main(String[] args) {
        GroupChatServer server = new GroupChatServer();
        server.listen();
    }
}
